﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;


namespace Hook.Common
{
    public static class Memory
    {
        const int PROCESS_ALL_ACCESS = 0x1F0FFF;
        const int PROCESS_VM_READ = 0x0010;
        const int PROCESS_VM_WRITE = 0x0020;

        public static int ReadMomeryToInt(int procId, string lpBaseAddressText)
        {
            return ReadMomery(procId, lpBaseAddressText, 4);
        }

        public static int WriteIntMomery(int procId, string lpBaseAddressText, int value)
        {
            procId = OpenProcess(PROCESS_ALL_ACCESS, false, procId);
            var GameHandle = new IntPtr(procId);
            int ipbase = Convert.ToInt32(lpBaseAddressText, 16);
            var WriteAddress = new IntPtr(ipbase);
            int or2 = 0;
            var array = BitConverter.GetBytes(value);
            int bytesWritten;
            var b = WriteProcessMemory(GameHandle, WriteAddress, array, (uint)array.Length, out bytesWritten);
            //var b = WriteProcessMemory(procId, ref ipbase, ref value, 4, ref or2);
            return 0;
        }

        private static int ReadMomery(int procId, string lpBaseAddressText, int length)
        {
            procId = OpenProcess(PROCESS_VM_READ | PROCESS_VM_WRITE, false, procId);
            var lpBuffer = IntPtr.Zero;
            int ipbase = Convert.ToInt32(lpBaseAddressText, 16);
            byte[] result = new byte[length];
            int r1 = 0;
            int or1 = 0;
            //Kernel32.ReadProcessMemory(hintp, lpBaseAddress, lpBuffer, 4, ref lpNumberOfBytesWritten);
            var b = ReadProcessMemory(procId, ipbase, out r1, 4, out or1);
            return r1;
        }

        [DllImport("kernel32.dll", SetLastError = true)]
        static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint nSize, out int lpNumberOfBytesWritten);

        [DllImport("kernel32.dll")]
        private static extern long GetLastError();

        [DllImport("Kernel32.dll")]
        private static extern bool ReadProcessMemory(int hProcess, int lpBaseAddress, out int lpBuffer, int nSize, out int lpNumberOfBytesRead);

        [DllImport("kernel32.dll")]
        private static extern int OpenProcess(uint dwDesiredAccess, bool bInheritHandle, int dwProcessId);
    }
}
